import { BinaryReader, BinaryWriter, ObjCoder } from "k-coder";
import { IMsgCoder } from "./defines";

const w = new BinaryWriter();
const r = new BinaryReader();

/**
 * 默认编解码
 */
export const coder: IMsgCoder = {

    encode(msgId: number, msg?: any): Buffer {
        w.start();
        w.uint = msgId;
        return ObjCoder.encode(msg, w).end() as Buffer;
    },

    decode(data: Buffer): { msgId: number, msg?: any } {
        r.start(data);
        let msgId = r.uint;
        let msg = ObjCoder.decode(r);
        return { msgId, msg };
    },

    decodeMsgId(data: Buffer): { msgId: number, msgBuf: Buffer } {
        r.start(data);
        let msg = { msgId: r.uint, msgBuf: r.cut(r.len - r.pos) as Buffer }
        return msg;
    },

    decodeMsgBuf(msgId: number, msgBuf: Buffer) {
        return msgBuf.length ? ObjCoder.decode(msgBuf) : undefined;
    }
}